package com.open.capacity.user.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysPost;
import com.open.capacity.user.service.SysPostService;
import com.open.capacity.user.vo.SysPostExcel;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.list.TreeList;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 岗位管理
 */
@RestController
@Api(tags = "岗位模块api")
public class SysPostController {

    private static Logger logger = LoggerFactory.getLogger(SysPostController.class);


    @Autowired
    private SysPostService postService;


    /**
     * 查询岗位
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('post:get/posts')")
    @ApiOperation(value = "查询岗位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "departmentId", value = "部门id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "parentId", value = "父级id", dataType = "String"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataType = "String")
    })
    @GetMapping("/posts")
    public Result<List<SysPost>> findPosts(@RequestParam Map<String, Object> params) {
        List<SysPost> list = postService.findPosts(params);
        return Result.succeed(list);
    }

    /**
     * 查询岗位tree
     *
     * @param companyId 公司id
     * @param parentId  上级id
     * @return
     */
    @PreAuthorize("hasAuthority('post:get/posts')")
    @ApiOperation(value = "查询岗位tree")
    @GetMapping("/posts/tree")
    public Result<List<TreeVo>> treePosts(@RequestParam(value = "companyId", defaultValue = "0") String companyId,
                                          @RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", companyId);
        List<SysPost> posts = postService.findPosts(params);
        List<TreeVo> treeList = new TreeList();
        posts.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(false);
            node.setParentId(m.getParentId());

            treeList.add(node);
        });

        return Result.succeed(TreeVo.RecursiveBuilder(treeList, parentId));
    }


    @ApiOperation(value = "获取岗位")
    @PreAuthorize("hasAuthority('post:get/posts/{id}')")
    @GetMapping("/posts/{id}")
    public Result<SysPost> findPostById(@PathVariable(value = "id") String id) {
        SysPost post = postService.findById(id);
        return Result.succeed(post);
    }


    @ApiOperation(value = "获取岗位名称")
    @PreAuthorize("hasAuthority('post:get/posts/getName')")
    @GetMapping("/posts/getName")
    public Result getPostName(@RequestParam(value = "keyValue") String keyValue) {
        SysPost post = postService.findById(keyValue);
        return Result.succeed(post == null ? "" : post.getName(), "获取成功！");
    }

    @ApiOperation(value = "获取岗位名称")
    @PreAuthorize("hasAuthority('post:get/posts/getName')")
    @GetMapping("/posts/getNames")
    public Result getPostNames(@RequestParam(value = "keyValue") String keyValue) {
        String nameStr = "";
        String[] arrIds = keyValue.split(",");
        for (String id : arrIds) {
            SysPost post = postService.findById(keyValue);
            if (post != null) {
                if (StringUtil.isEmpty(nameStr)) {
                    nameStr += post.getName();
                } else {
                    nameStr += "," + post.getName();
                }
            }
        }
        return Result.succeed(nameStr, "获取成功！");
    }


    /**
     * 岗位新增或者更新
     *
     * @param sysPost
     * @return
     */
    @PreAuthorize("hasAnyAuthority('post:post/posts','post:put/posts')")
    @ApiOperation(value = "保存岗位")
    @PostMapping("/posts/saveOrUpdate")
    @LogAnnotation(module = "岗位", name = "更新")
    public Result saveOrUpdate(@RequestBody SysPost sysPost, String keyValue) {
        return postService.saveOrUpdate(sysPost, keyValue);
    }

    /**
     * 删除岗位
     * delete /posts/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('post:delete/posts/{id}')")
    @ApiOperation(value = "删除岗位")
    @DeleteMapping("/posts/{id}")
    @LogAnnotation(module = "岗位", name = "删除")
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            postService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 导出数据
     *
     * @return
     */
    @GetMapping("/postexcel/export")
    @PreAuthorize("hasAuthority('post:post/posts/export')")
    public void export(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        List<SysPostExcel> result = postService.findExcels(params);

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=posts.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
                SysPostExcel.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
